# -*- coding: utf-8 -*-
# flake8: noqa
from flask import Blueprint, request, make_response, render_template, Response
from qiniu import Auth, put_data
from app.config import create_db_connection
import datetime
from app.config import generate_random_string
from urllib.parse import quote
import logging
import json

# 七牛云配置信息
access_key = 'YMj_ZtFBc6fBTfaLlb2dAw7rahOYAAsAeC7xnEAz'
secret_key = 'm6Zw_W-OC9ONGeIS2eQNS39ZhPofqGvmhXsFZpvS'
bucket_name = 'btnetdisc'
# 七牛云的域名
domain = 'sfxsszjdh.hn-bkt.clouddn.com'
# 创建七牛云的认证对象

main_bp = Blueprint('main', __name__)

@main_bp.route('/')
def index():
    return render_template('index.html')


def download_qiniu_file(access_key, secret_key, domain, key):
    q = Auth(access_key, secret_key)
    base_url = f'http://{domain}/{key}'
    private_url = q.private_download_url(base_url)
    return private_url

@main_bp.route('/download_file/<string:url>', methods=('POST', 'GET'))
def download_file(url):
    conn, cursor = create_db_connection()

    query = "SELECT * FROM tmp_files WHERE file_url = %s"
    cursor.execute(query, (url,))
    result = cursor.fetchone()
    cursor.close()
    conn.close()
    storage_name = result[2]
    encoded_storage_name = quote(storage_name)  # 对文件名进行编码

    private_url = download_qiniu_file(access_key, secret_key, domain, storage_name)
    print(private_url)
    response = make_response(private_url)
    response.headers['Content-Type'] = 'application/octet-stream'
    response.headers['Content-Disposition'] = f'attachment; filename="{encoded_storage_name}"'

    return response

@main_bp.route('/file_info/<string:url>')
def file_info(url):
    conn, cursor = create_db_connection()

    query = "SELECT * FROM tmp_files WHERE file_url = %s"
    cursor.execute(query, (url,))
    result = cursor.fetchone()

    cursor.close()
    conn.close()

    print(result)

    def convert_bytes_to_unit(bytes_size):
        units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
        unit_index = 0
        while bytes_size >= 1024 and unit_index < len(units) - 1:
            bytes_size /= 1024
            unit_index += 1
        return f"{round(bytes_size, 2)} {units[unit_index]}"

    file_info = result

    file_size = convert_bytes_to_unit(result[4])
    print(file_size)

    file_name = result[2]

    return render_template('file_info.html', file_info=file_info, file_size=file_size)

@main_bp.route('/token', methods=['POST', 'GET'])
def get_token():
    try:
        q = Auth(access_key, secret_key)
        token = q.upload_token(bucket_name)
        return Response(json.dumps({'token': token, 'domain': domain}), status=200, mimetype='application/json')
    except Exception as e:
        error_message = f"Error generating token: {str(e)}"
        app.logger.error(error_message)  # 记录更详细的错误日志
        return Response(json.dumps({'error': error_message}), status=500, mimetype='application/json')

@main_bp.route('/upload_success', methods=['POST',])
def upload_success():
    file_name = request.form.get('key')
    file_size = request.form.get('fileSize')

    print(file_name,file_size)
    url_id = generate_random_string()

    # 获取当前上传时间
    upload_time = datetime.datetime.now()

    # 假设您有一个函数来计算过期时间，例如 1 天后过期
    expiration_time = datetime.datetime.now() + datetime.timedelta(days=1)
    print(expiration_time)

    # 假设您想要模拟一个成功的状态，直接进行后续操作
    conn, cursor = create_db_connection()
    cursor.execute('''
                   INSERT INTO tmp_files (file_url, file_name, storage_name, file_size, expiration_time, upload_time)
                   VALUES (%s, %s, %s, %s, %s, %s)
               ''', (url_id, file_name, file_name, file_size, expiration_time, upload_time))
    conn.commit()
    cursor.close()
    conn.close()
    url_id = 'file_info/'+url_id
    return Response(json.dumps({'url_id': url_id}), status=200, mimetype='application/json')